package com.example.bootDemo.controller;

import com.example.bootDemo.entity.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @description: 创建登录类
 * @author: zys
 * @create: 2021-04-09 16:58
 **/
@RestController
public class LoginController {

    /**
     * 登录校验接口
     */
    @PostMapping("/login")
    public String login(User user) {
        //添加用户认证信息
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(
                user.getUserName(), user.getPassword()
        );
        try {
            //进行验证,捕获相应的异常，然后返回对应信息
            subject.login(usernamePasswordToken);
            /*subject.checkRole("admin");
            subject.checkPermissions("query", "add");*/
        } catch (AuthenticationException e) {
            e.printStackTrace();
            return "账号或密码错误！";
        } catch (AuthorizationException e) {
            e.printStackTrace();
            return "没有权限";
        }
        return "login success!";
    }

    /**
     * 注解检验角色和权限
     */
    @RequiresRoles("admin")
    @RequiresPermissions("add")
    @GetMapping("/index")
    public String index() {
        return "index!";
    }

}
